import {MutationTree} from "vuex";
import storeUtils from "@/utils/storeUtils";

const mutations: MutationTree<any> = {
    SET_COLLAPSE(state: any, collapse: any): void {
        state.collapse = collapse;
        storeUtils.setStorageS(storeUtils.CONST.collapse, state.collapse);

    },
    SET_PROJECT_INFO(state: any, projectInfo: any): void {
        state.projectInfo = projectInfo;
        storeUtils.setStorageS(storeUtils.CONST.projectInfo, state.projectInfo);
    },

    SET_BROWSER_HEADER_TITLE: (state, title) => {
        state.browserHeaderTitle = title;
    },

    ADD_VISITED_VIEW: (state, view) => {
        if (state.visitedViews.some((v: any) => v.path === view.path)) {
            return;
        }
        state.visitedViews.push(
            Object.assign({}, view, {
                title: view.meta.title || 'no-name'
            })
        );
    },

    ADD_CACHED_VIEW: (state, view) => {
        if (state.cachedViews.includes(view.name)) {
            return;
        }
        if (view.meta.cache) {
            state.cachedViews.push(view.name);
        }
    },
    UPDATE_VISITED_VIEW: (state, view) => {
        for (let v of state.visitedViews) {
            if (v.path === view.path) {
                v = Object.assign(v, view);
                break;
            }
        }
    },
    DEL_CACHED_VIEW: (state, view) => {
        for (const i of state.cachedViews) {
            if (i === view.name) {
                const index = state.cachedViews.indexOf(i);
                state.cachedViews.splice(index, 1);
                break;
            }
        }
    },
    DEL_VISITED_VIEW: (state, view) => {
        for (const [i, v] of state.visitedViews.entries()) {
            if (v.path === view.path) {
                state.visitedViews.splice(i, 1);
                break;
            }
        }
    },
    DEL_OTHERS_VISITED_VIEWS: (state, view) => {
        state.visitedViews = state.visitedViews.filter((v: any) => {
            return v.meta.affix || v.path === view.path;
        });
    },
    DEL_OTHERS_CACHED_VIEWS: (state, view) => {
        for (const i of state.cachedViews) {
            if (i === view.name) {
                const index = state.cachedViews.indexOf(i);
                state.cachedViews = state.cachedViews.slice(index, index + 1);
                break;
            }
        }
    },

    DEL_ALL_VISITED_VIEWS: state => {
        // keep affix tags
        state.visitedViews = state.visitedViews.filter((tag: any) => tag.meta.affix);
    },
    DEL_ALL_CACHED_VIEWS: state => {
        state.cachedViews = [];
    },
    TOGGLE_DEVICE: (state, device) => {
        state.device = device
    },
};

export default mutations;
